/* Copyright (c) 2010 Sven Weidauer
 
 Permission is hereby granted,free of charge,to any person obtaining a copy of this software and associated documentation files (the "Software"),to deal in the Software without restriction,including without limitation the rights to use,copy,modify,merge,publish,distribute,sublicense,and/or sell copies of the Software,and to permit persons to whom the Software is furnished to do so,subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS",WITHOUT WARRANTY OF ANY KIND,EXPRESS OR IMPLIED,INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,DAMAGES OR OTHER LIABILITY,WHETHER IN AN ACTION OF CONTRACT,TORT OR OTHERWISE,ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */

#include <Platform/Events.h>
#include <Platform/Atomics.h>

#include "EventInternal.h"

#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <sys/time.h>
#include <sys/errno.h>

typedef struct CondVar {
	pthread_cond_t condition;
	pthread_mutex_t mutex;
} CondVar;

static CondVar *CondVarCreate()
{
	CondVar *result = malloc( sizeof( CondVar ) );
	if (0 == result) return 0;
	
	int ret = pthread_cond_init( &result->condition, 0 );
	if (0 != ret) {
		free( result );
		return 0;
	}
	
	ret = pthread_mutex_init( &result->mutex, 0 );
	if (0 != ret) {
		pthread_cond_destroy( &result->condition );
		free( result );
		return 0;
	}
	
	return result;
}

static void CondVarDestroy( CondVar *cv )
{
	assert( cv );
	
	pthread_mutex_destroy( &cv->mutex );
	pthread_cond_destroy( &cv->condition );
	
	free( cv );
}

typedef struct ListNode {
	struct ListNode *next, *prev;
	CondVar *cv;
} ListNode;


static ListNode *NodeCreate( CondVar *cv ) 
{
	ListNode *result = malloc( sizeof( ListNode ) );
	if (0 == result) return 0;	
	result->next = 0;
	result->prev = 0;
	result->cv = cv;
	return result;
}



static void Event_RemoveWaiter( MPEvent event, ListNode *node )
{
	assert( event && node );
    
    pthread_mutex_lock( &event->listMutex );
	
	if (node->prev) node->prev->next = node->next;
	if (node->next) node->next->prev = node->prev;
	
	if (node == event->head) event->head = node->next;
	if (node == event->tail) event->tail = node->prev;
    
    pthread_mutex_unlock( &event->listMutex );
	
	free( node );
}

void MPRetainEvent( MPEvent event )
{
	assert( event );
	MPAtomicIncrement( &event->refCount );
}



static void Event_AddWaiter( MPEvent event, ListNode *new ) 
{
	assert( event && new );
	
    pthread_mutex_lock( &event->listMutex );
    
	if (!event->head) event->head = new;
	new->prev = event->tail;
	if (event->tail) event->tail->next = new;
	event->tail = new;
    
    pthread_mutex_unlock( &event->listMutex );
    
    MPRetainEvent( event );
}

static void Event_UnRef( MPEvent event )
{
	assert( event );
	if (0 == MPAtomicDecrement( &event->refCount )) {
		assert( 0 == event->head && 0 == event->tail );
        pthread_mutex_destroy( &event->listMutex );
		free( event );
	}
}

static void RemoveListNodes( unsigned count, MPEvent *events, ListNode **nodes )
{
	assert( events && nodes );
	for (unsigned index = 0; index < count; index++) {
		if (!events[index]) continue;
		if (nodes[index]) {
			Event_RemoveWaiter( events[index], nodes[index] );
			Event_UnRef( events[index] );
		}
	}
}

static int FindSignalledEvent( unsigned count, MPEvent *events )
{
    assert( events );
    for (unsigned i = 0; i < count; i++) {
        if (events[i]->signalled) return i;
    }
    return -1;
}

static void AutoResetEvent( MPEvent ev )
{
    if (!ev->manualReset) ev->signalled = false;
}

static bool CalculateTimeout( struct timespec *tp, long timeout )
{
    struct timeval now;
    if (gettimeofday( &now, 0 ) != 0) return false;
    
    int seconds = timeout / 1000;

    tp->tv_sec = now.tv_sec + seconds;
    tp->tv_nsec = now.tv_usec * 1000 + (timeout - seconds * 1000) * 1000000;
    
    if (tp->tv_nsec >= 1000000000) {
        tp->tv_nsec -= 1000000000;
        tp->tv_sec += 1;
    }
    
    return true;
}

static bool ConditionWaitWithTimeout( CondVar *cv, int timeout, struct timespec *tp )
{
    if (MP_TIMEOUT_FOREVER == timeout) {
        pthread_cond_wait( &cv->condition, &cv->mutex );
        return true;
    } else {
        int rc = pthread_cond_timedwait( &cv->condition, &cv->mutex, tp );
        if (ETIMEDOUT == rc) pthread_mutex_unlock( &cv->mutex );
        return rc != ETIMEDOUT;
    }
}

MPWaitResult MPWaitForAnyEvent( unsigned count, MPEvent *events, int timeout )
{
	if (0 >= count || count > MP_MAX_EVENTS) return MP_WAIT_ERROR;
	
	assert( events );
    
    struct timespec tp;
    if (MP_TIMEOUT_FOREVER != timeout) {
        if (!CalculateTimeout( &tp, timeout )) return MP_WAIT_ERROR;
    }
	
	CondVar *cv = CondVarCreate();
	if (0 == cv) return MP_WAIT_ERROR;
	
	ListNode *nodes[count];

	for (unsigned index = 0; index < count; index++) {
		assert( events[index] );
		
		nodes[index] = NodeCreate( cv );
		if (!nodes[index]) {
			RemoveListNodes( index, events, nodes );
			CondVarDestroy( cv );
			return MP_WAIT_ERROR;
		}
		
		Event_AddWaiter( events[index], nodes[index] );
	}
	
	pthread_mutex_lock( &cv->mutex );
    int signalledIndex = -1;
    while (-1 == (signalledIndex = FindSignalledEvent( count, events ))) {
        if (!ConditionWaitWithTimeout( cv, timeout, &tp )) {
            RemoveListNodes( count, events, nodes );
            CondVarDestroy( cv );
            return MP_WAIT_TIMEOUT;
        }
    }
    AutoResetEvent( events[signalledIndex] );
    
	pthread_mutex_unlock( &cv->mutex );
	
	RemoveListNodes( count, events, nodes );
    CondVarDestroy( cv );
    
	return MP_WAIT_EVENT_0 + signalledIndex;
}

static void DestroyCVs( unsigned count, CondVar **cvs )
{
	for (unsigned index = 0; index < count; index++) {
		if (cvs[index]) CondVarDestroy( cvs[index] );
	}
}

MPWaitResult MPWaitForAllEvents( unsigned count, MPEvent *events, int timeout )
{
	if (0 >= count || count > MP_MAX_EVENTS) {
        DEBUG_PRINT( "Invalid event count %d", count );
        return MP_WAIT_ERROR;        
    }
	
	assert( events );
    
    struct timespec tp;
    if (MP_TIMEOUT_FOREVER != timeout) {
        if (!CalculateTimeout( &tp, timeout )) {
            DEBUG_PRINT( "Cannot compute timeout (%d)", timeout );
            return MP_WAIT_ERROR;            
        }
    }
    
	CondVar *cvs[count];
	
	for (unsigned index = 0; index < count; index++) {
		cvs[index] = CondVarCreate();
		if (!cvs[index]) {
            DEBUG_PRINT( "Cannot create condition variable for event %d", index );
			DestroyCVs( index, cvs );
			return MP_WAIT_ERROR;
		}
	}
	
	ListNode *nodes[count];
	
	for (unsigned index = 0; index < count; index++) {
		nodes[index] = NodeCreate( cvs[index] );
		if (!nodes[index]) {
            DEBUG_PRINT( "Cannot create list node for event %d", index );
			RemoveListNodes( index, events, nodes );
			DestroyCVs( count, cvs );
			return MP_WAIT_ERROR;
		}
		Event_AddWaiter( events[index], nodes[index] );
	}
	
	for (unsigned index = 0; index < count; index++) {
		pthread_mutex_lock( &cvs[index]->mutex );
        while (!events[index]->signalled) {
            if (!ConditionWaitWithTimeout( cvs[index], timeout, &tp )) {
                DEBUG_PRINT( "Timeout" );
                RemoveListNodes( count, events, nodes );
                DestroyCVs( count, cvs );
                return MP_WAIT_TIMEOUT;
            }
        }
		pthread_mutex_unlock( &cvs[index]->mutex );
	}
	
	for (unsigned index = 0; index < count; index++) {
		AutoResetEvent( events[index] );
	}
	
    RemoveListNodes( count, events, nodes );
	DestroyCVs( count, cvs );
	
	return MP_WAIT_FINNISHED;
}

MPWaitResult MPWaitForEvent( MPEvent event, int timeout )
{
    return MPWaitForAnyEvent( 1, &event, timeout );
}

#define TEST_BIT( set, flag ) (((set) & (flag)) == (flag))

bool MPInitializeEvent( MPEvent event, MPEventParameters parameters )
{
    int ret = pthread_mutex_init( &event->listMutex, 0 );
    if (0 != ret) return false;
    
    event->refCount = 1;
    event->head = event->tail = 0;
    event->signalled = TEST_BIT( parameters, MP_EVENT_CREATE_SIGNALED );
    event->manualReset = TEST_BIT( parameters, MP_EVENT_MANUAL_RESET );
    
    return true;
}

bool MPCreateEvent( MPEvent *outEvent, MPEventParameters parameters )
{
    if (!outEvent) return false;
    
    MPEvent result = malloc( sizeof( MPEventInternal ) );
    if (!result) return false;
    
    if (!MPInitializeEvent( result, parameters )) {
        free( result );
        return false;
    }
    
    *outEvent = result;
    return true;
}

bool MPSetEvent( MPEvent event )
{
    event->signalled = true;

    for (ListNode *node = event->head; 0 != node; node = node->next) {
        pthread_mutex_lock( &node->cv->mutex );
    }
    
    for (ListNode *node = event->head; 0 != node; node = node->next) {
        pthread_cond_broadcast( &node->cv->condition );
    }
    
    for (ListNode *node = event->head; 0 != node; node = node->next) {
        pthread_mutex_unlock( &node->cv->mutex );
    }
    
    return true;
}

bool MPResetEvent( MPEvent event )
{
    event->signalled = false;
    return true;
}

bool MPReleaseEvent( MPEvent *inoutEvent )
{
    if (!(inoutEvent && *inoutEvent)) return false;
    
    Event_UnRef( *inoutEvent );
    *inoutEvent = 0;
    
    return true;
}
